package com.easyskool.composer;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.easyskool.constants.CommonConstants;
import com.easyskool.constants.EmailLinkConstants;
import com.easyskool.dao.BaseDao;
import com.easyskool.exception.DaoException;
import com.easyskool.hibernate.model.AccessGroupMapper;
import com.easyskool.hibernate.model.AccessGroups;
import com.easyskool.hibernate.model.Schools;
import com.easyskool.hibernate.model.UserAuthorization;
import com.easyskool.hibernate.model.UserProfiles;
import com.easyskool.util.HibernateUtil;
import com.easyskool.util.mailUtil;
import com.easyskool.utilfunction.NullObjects;
import com.easyskool.utilfunction.UtilFunctions;
import com.ivp.cloud.stratus.logger.LoggingUtil;

public class IdentityModuleComposer {

	private static LoggingUtil logger = (LoggingUtil) LoggingUtil
			.getLogger(IdentityModuleComposer.class.getName());


	 
	/**
	 * If user access group is admingroup then all the groups with createdby=
	 * default will be sent back to the user else only those default groups will
	 * be sent whose persmissions are with that particular user
	 * 
	 * @param userAccessGroup
	 * @return
	 * @throws Exception 
	 */
	public List<AccessGroups> getDefaultGroups(String userAccessGroup,Schools school) throws Exception {

		if (CommonConstants.ADMIN_GROUP.equals(userAccessGroup)) {
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("createdBy", "default");
			List<AccessGroups> ags = new ArrayList<AccessGroups>();
			try {
				ags = HibernateUtil.baseDaoStatic.find(AccessGroups.class, whereMap);
			} catch ( Exception e) {
				e.printStackTrace();
			}
			return ags;
		} else {
			HashMap<String, Object> whereMap = new HashMap<String, Object>();
			List<AccessGroups> ags = new ArrayList<AccessGroups>();
			List<AccessGroupMapper> agms = new ArrayList<AccessGroupMapper>();
			try {
				AccessGroups CustomGroupCode = new AccessGroups();
				CustomGroupCode.setAgCode(userAccessGroup);
				whereMap.put("accessGroupsByAgmCustomGroupCode",
						CustomGroupCode);
				whereMap.put("schools",
						school);
				agms = HibernateUtil.baseDaoStatic
						.customQuery(
								"from AccessGroupMapper where accessGroupsByAgmCustomGroupCode =:accessGroupsByAgmCustomGroupCode and schools=:schools",
								whereMap);
				for (int i = 0; i < agms.size(); i++) {
					ags.add(agms.get(i).getAccessGroupsByAgmDefaultGroupCode());
				}
			} catch (DaoException e) {
				e.printStackTrace();
			}

			return ags;
		}
	}

	public int saveCustomGroup(String user,String desc,String groupName, ArrayList<String> groups, Schools school) {
		
		AccessGroups ags =new AccessGroups();
		ags.setAgName(groupName);
		ags.setAaDescription(desc);
		ags.setAgCode(groupName);
		ags.setCreatedBy(user);
		ags.setModifiedBy(user);
		ags.setCreatedDate(new Date());
		ags.setStatus(1);
		ags.setSchools(school);
		ags.setModifiedDate(new Date());
		int flag=0;
		try {
			   HibernateUtil.baseDaoStatic.insertWithObject(AccessGroups.class, ags);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("Error in storing ags "+ user +" "+e);
			return 0;
		}
		try{
		for (int i=0;i<groups.size();i++)
		{
			AccessGroups custom=new AccessGroups();
			custom.setAgCode(groupName);
			AccessGroups defaultGroup=new AccessGroups();
			defaultGroup.setAgCode(groups.get(i));
			AccessGroupMapper agm =new AccessGroupMapper();
			agm.setAccessGroupsByAgmDefaultGroupCode(defaultGroup);
			agm.setAccessGroupsByAgmCustomGroupCode(custom);
			agm.setCreatedBy(user);
			agm.setModifiedBy(user);
			agm.setSchools(school);
			agm.setCreatedDate(new Date());
			agm.setModifiedDate(new Date());
			HibernateUtil.baseDaoStatic.insertWithObject(AccessGroupMapper.class, agm);
		}
		}
		catch(Exception e)
		{
			logger.error("Error in storing agm "+ user +" " +e);
			return 0;
		}
		
		return 1;
	}
public int insertUser(String user, String email,String groupName,  Schools school) {
		
	AccessGroups ags= new AccessGroups();
	ags.setAgCode(groupName);
	String dummy="No Data";
		UserAuthorization ua= new UserAuthorization(UtilFunctions.generateString(10), dummy,    school,   ags, dummy  ,   dummy,    dummy,   dummy, dummy  , dummy  ,email, 0, user, new Date(), user,new Date()  );
		int flag=0;
		try {
			  if( HibernateUtil.baseDaoStatic.insertWithObject(UserAuthorization.class, ua)!=null)
				  flag=0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("Error in storing ags "+ user +" "+e);
			return 0;
		}
	 logger.info("Sending Email to "+user+" "+" EMail: "+ email);
	 new mailUtil(email ,EmailLinkConstants.ACCOUNT_CREATED,EmailLinkConstants.EMAIL_MSG_CONTENT);
		
		return 1;
	}
	public int updateCustomGroup(String user,String desc,String code,HashMap<String,Integer> newgroups, Schools school) throws Exception {
		 
		Map<String, Object> whereMap = new HashMap<String, Object>();
		AccessGroups ag=new AccessGroups();
		ag.setAgCode(code);
		whereMap.put("accessGroupsByAgmCustomGroupCode",ag);
		List<AccessGroupMapper> toBeDeleted = new ArrayList<AccessGroupMapper>();
		try {
			toBeDeleted = HibernateUtil.baseDaoStatic.find(AccessGroupMapper.class, whereMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		for(int i=0;i<toBeDeleted.size();i++)
		{
			if(newgroups.containsKey(toBeDeleted.get(i).getAccessGroupsByAgmDefaultGroupCode().getAgCode()))
			{
				newgroups.remove(toBeDeleted.get(i).getAccessGroupsByAgmDefaultGroupCode().getAgCode());
				toBeDeleted.remove(i);
				i--;
			}
		}
		for(int i=0;i<toBeDeleted.size();i++)
		{
		HibernateUtil.baseDaoStatic.delete(toBeDeleted.get(i) );
		}
		Iterator it = newgroups.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry) it.next();
			System.out.println(pairs.getKey() + " = " + pairs.getValue());
			AccessGroupMapper agm = new AccessGroupMapper();
			AccessGroups ags = new AccessGroups();
			ags.setAgCode(code);
			agm.setAccessGroupsByAgmCustomGroupCode(ags);
			AccessGroups ags1 = new AccessGroups();
			ags1.setAgCode((String) pairs.getKey());
			agm.setAccessGroupsByAgmDefaultGroupCode(ags1);
			agm.setSchools(school);
			agm.setCreatedBy(user);
			agm.setModifiedBy(user);
			agm.setCreatedDate(new Date());
			agm.setModifiedDate(new Date());
			HibernateUtil.baseDaoStatic.insertWithObject(AccessGroupMapper.class, agm);
			it.remove(); // avoids a ConcurrentModificationException
		}


		
		return 1;
	}
	public List<AccessGroups> getCustomGroups(String user,String accessGroup,Schools school) throws Exception {

		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("schools",school);
		
		List<AccessGroups> ags = new ArrayList<AccessGroups>();
		try {
			if(accessGroup.equals(CommonConstants.ADMIN_GROUP))
			ags = HibernateUtil.baseDaoStatic.find(AccessGroups.class, whereMap);
			else
			{
				whereMap.put("createdBy",user);
				ags = HibernateUtil.baseDaoStatic.find(AccessGroups.class, whereMap);
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return ags;
	}
	public List<AccessGroupMapper> getCustomGroup(String user,String code) {

		logger.info("Data entering getCustomGroup "+user+" "+code);
		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("createdBy",user);
		AccessGroups agm =new AccessGroups();
		agm.setAgCode(code);
		whereMap.put("accessGroupsByAgmCustomGroupCode",agm);
		
		List<AccessGroupMapper> ags = new ArrayList<AccessGroupMapper>();
		try {
			ags = HibernateUtil.baseDaoStatic.find(AccessGroupMapper.class, whereMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ags;
	}

	public int deleteCustomGroup(String user, String groupCode, Schools school) {

		HashMap<String, Object> whereMap = new HashMap<String, Object>();
		System.out.println(school.getSchoolCode());
		AccessGroups ag= new AccessGroups();
		ag.setAgCode(groupCode);
		whereMap.put("accessGroupsByAgmCustomGroupCode",ag);
		int res=0;
		try {
			 HibernateUtil.baseDaoStatic.customQueryCUD("delete from AccessGroupMapper where accessGroupsByAgmCustomGroupCode=:accessGroupsByAgmCustomGroupCode" , whereMap);
			 
				whereMap.clear();
				whereMap.put("agCode",groupCode);
				whereMap.put("schools",school);
			 HibernateUtil.baseDaoStatic.customQueryCUD("delete from AccessGroups where agCode=:agCode and schools=:schools" , whereMap);
//				res=HibernateUtil.baseDaoStatic.deleteWithoutFullObject(AccessGroups.class, whereMap);
		 
		} catch ( Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return res;
		}
		return res;
	}


	public List<UserAuthorization> getUsers( String user,Schools school,String accessGroup) {

		AccessGroups ag= new AccessGroups();
		ag.setAgCode(accessGroup);
		HashMap<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("schools",school);
		whereMap.put("status",1);
		List<UserAuthorization> ags = new ArrayList<UserAuthorization>();
		try {
			if(accessGroup.equals(CommonConstants.ADMIN_GROUP))
			ags = HibernateUtil.baseDaoStatic.find(UserAuthorization.class, whereMap);
			else
			{	whereMap.put("createdBy",user);
				ags = HibernateUtil.baseDaoStatic.find(UserAuthorization.class, whereMap);	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ags;
	}


	public int updateUser(String user, String group, String uCode) throws Exception {
		Map<String, Object> whereClause =new HashMap<String, Object>();
		whereClause.put("uaCode", uCode);
		AccessGroups ags=new AccessGroups();
		ags.setAgCode(group);
		Map<String, Object> updateClause =new HashMap<String, Object>();
		updateClause.put("modifiedBy", user);
		updateClause.put("modifiedDate", new Date());
		updateClause.put("accessGroups", ags);
		return HibernateUtil.baseDaoStatic.updateWithoutFullobject(UserAuthorization.class, whereClause, updateClause);
		 
	}
	public int deleteUser(String user, String uCode) throws Exception {
		Map<String, Object> whereClause =new HashMap<String, Object>();
		logger.info("User: "+user+", uCode: "+uCode);
		whereClause.put("uaCode", uCode);
		Map<String, Object> updateClause =new HashMap<String, Object>();
		updateClause.put("modifiedBy", user);
		updateClause.put("modifiedDate", new Date());
		updateClause.put("status", 2);
		return HibernateUtil.baseDaoStatic.updateWithoutFullobject(UserAuthorization.class, whereClause, updateClause);
		 
	}
	
	
}
